<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>move move!!!</title>
	<style>
		html,body,div{margin: 0;padding: 0;box-sizing: border-box;}
		.box{height: 100px;width: 100px;background-color: #f66;}
	</style>
</head>
<body>
	<div class="box" id="box"></div>
	<script>
		var box = document.getElementById('box');
		var _top = + box.style.marginTop;
		var _left = + box.style.marginLeft;

		/*获取内容区域的宽高*/
		var winwidth = window.innerWidth;
		var winheight = window.innerHeight;


		/*键位绑定*/
		document.onkeydown = function (e) {
			/*up*/
			if(_top >= 50 && e.keyCode == 38){
	            	_top -= 50;
			}else if(e.keyCode == 38){
	            	_top = 0;
			}

			/*down*/
            if(_top <= winheight-150 && e.keyCode == 40){  
	            	_top += 50;
            }else if(e.keyCode == 40){
            		_top = winheight-100;
            }

            /*left*/
            if(_left >= 50 && e.keyCode == 37){
	            	_left -= 50;
            }else if(e.keyCode == 37){
	            	_left = 0;
            }
            
            /*right*/
            if(_left <= winwidth-150 && e.keyCode == 39){
	            	_left += 50;
            }else if(e.keyCode == 39){
	            	_left = winwidth-100;
            }
            
            
            box.style.marginTop = _top + 'px';
            box.style.marginLeft = _left + 'px';
	    }
	</script>
</body>
</html>
